package org.test.elasticsearch.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.test.elasticsearch.core.Student;
import org.test.elasticsearch.dao.ElasticsearchDao;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;

/**
 * @author LHB
 * @date 2019/12/9 15:00
 */
public class StudentService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @PostConstruct
    public void test() {

        //  elasticsearchTemplate.deleteIndex(Student.class);
        Boolean exists = elasticsearchTemplate.indexExists(Student.class);
        System.out.println(exists);
        if (!exists) {
            elasticsearchTemplate.createIndex(Student.class);
            List<IndexQuery> lists = new ArrayList<>();
            Student student = new Student();
            student.setAge("13");
            student.setId(1);
            student.setName("小明");
            student.setSex("男");
            IndexQuery indexQuery = new IndexQueryBuilder().withId("1").withObject(student).build();
            lists.add(indexQuery);
            elasticsearchTemplate.bulkIndex(lists);
        }
        List<Student> students = findAll();
        System.out.println(students.get(0));
    }


    //查询数据
    public List findAll() {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(matchAllQuery()).build();
        return elasticsearchTemplate.queryForList(searchQuery, Student.class);
    }


}
